package myta.base;

import java.sql.SQLException;
import java.util.Map;

import javax.faces.context.FacesContext;

import myta.service.Database;
import myta.service.Utility;

public abstract class FormDataBase implements FormDataInterface{
	public String formName;
	
	public FormDataBase() {
		try {
			if(Database.dbConnection == null){
				Database.connectToDatabase();
			}
			
			Utility.checkAuth();
			
			init();
			
			if(Utility.isNew()){
				generateID();
			}else{
				FacesContext fc = FacesContext.getCurrentInstance();
				Map<String, String> map = fc.getExternalContext().getRequestParameterMap();
				getRequestData(map);
			}
		} catch (Exception e) {
			Utility.showMessage(e.getMessage());
			System.out.println(e);
		}
	}
	
	public String save(){
		try {
			Database.dbConnection.setAutoCommit(false);
			boolean boo = true;
			
			if(Utility.isNew()){
				boo = simpan();
			}else{
				boo = ubah();
			}
			
			if(boo){
				Database.dbConnection.commit();
				Utility.setNew(true);
				return formName + ".jsf?faces-redirect=true";
			}else{
				Database.dbConnection.rollback();
				Utility.showMessage("save error");
				System.out.println("save error");
				return "";
			}
		} catch (Exception e) {
			try {
				Database.dbConnection.rollback();
				Utility.showMessage(e.getMessage());
				System.out.println(e);
			} catch (SQLException e1) {}
			
			return "";
		}
	}
	
	public boolean beforeCancel(){
		return true;
	}
	
	public String cancel(){
		if(beforeCancel()){
			Utility.setNew(true);
			return formName + ".jsf?faces-redirect=true";
		}else{
			return "";
		}
	}
}
